package com.bestcem.xm.survey.export.type;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.survey.export.BaseTypeHandler;
import com.bestcem.xm.survey.grpc.client.dto.QstructsDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

import static com.bestcem.xm.survey.enums.QuestionTypeEnum.QUESTION_TYPE_BLANK;

@Slf4j
@Component
public class BlankHandler implements BaseTypeHandler {

    @Override
    public Map<String, String> getOpenColumnChangeDictV2(JSONObject data) {
        Map<String, String> res = new HashMap(2);
        res.put(getOpenRealcolV2(data), getOpenReadablecolV2(data));
        return res;
    }

    private String getOpenReadablecolV2(JSONObject data) {
        return BaseTypeHandler.clearHtml(data.getString("title"));
    }

    private String getOpenRealcolV2(JSONObject data) {
        return String.format("%s__open", data.getString("cid"));
    }

    @Override
    public List<String> getOpenColumnListV2(JSONObject data) {
        return Arrays.asList(getOpenRealcolV2(data));
    }

    @Override
    public Map<Object, Object> getOpenAnswerDictV2(JSONObject dataValue, Object answers) {
        Map<Object, Object> data = new HashMap<>();
        if (Objects.isNull(answers)) {
            //np.nan 可以理解为null
            data.put(getOpenRealcolV2(dataValue), null);
        } else {
            if (ObjectUtil.isNotEmpty(answers)) {
                //三叶草一般填空题答案不是数组
                if (answers instanceof List) {
                    data.put(getOpenRealcolV2(dataValue), BaseTypeHandler.clearHtml(String.valueOf(((List) answers).get(0))));
                } else if (answers instanceof String) {
                    data.put(getOpenRealcolV2(dataValue), BaseTypeHandler.clearHtml((String) answers));
                } else {
                    //np.nan 可以理解为null
                    data.put(getOpenRealcolV2(dataValue), null);
                }
            } else {
                data.put(getOpenRealcolV2(dataValue), null);
            }
        }
        return data;
    }

    @Override
    public List<List<String>> getVarLabelsV2(JSONObject dataValue, boolean not01, boolean need_title) {
        List<List<String>> data = new ArrayList<>();
        List<String> var_list = new ArrayList(), val_list = new ArrayList();
        var_list.add(String.format("VARIABLE LABELS %s__open '%s'.", dataValue.getString("cid"), getUnquotedStr(dataValue.getString("title"), false)));
        data.add(var_list);
        data.add(val_list);
        return data;
    }

    @Override
    public List<String> getSpssCodeV2(JSONObject param, QstructsDto qstruct) {
        List<String> head_list = new ArrayList();
        head_list.add(String.format("%s__open", param.getString("cid")));
        return head_list;
    }

    @Override
    public String getQuestionTypeValue() {
        return QUESTION_TYPE_BLANK.getValue();
    }
}
